package com.example.city_home_app.Activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.city_home_app.R;
import com.example.city_home_app.UI.PhotoViewAdapter;
import com.example.city_home_app.UI.PhotoViewPager;
import com.example.city_home_app.UI.UIUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import tv.danmaku.ijk.media.player.pragma.DebugLog;

public class PhotoViewActivity extends BaseActivity {
    @BindView(R.id.tv_image_count)
    TextView tvImageCount;
    @BindView(R.id.view_pager_photo)
    ViewPager viewPagerPhoto;
    @BindView(R.id.tv_save_image_photo)
    TextView tvSaveImagePhoto;


    private int currentPosition;
    private PhotoViewAdapter adapter;
    private ArrayList<String> Urls;

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_photo;
    }

    @Override
    protected void initViews() {
        super.initViews();
        ButterKnife.bind(this);

    }

    @Override
    protected void initData() {
        super.initData();
        Intent intent = getIntent();

        currentPosition = intent.getIntExtra("currentPosition", 0);
        Urls = intent.getStringArrayListExtra("urls");

        adapter = new PhotoViewAdapter(Urls, this);
        viewPagerPhoto.setAdapter(adapter);
        viewPagerPhoto.setCurrentItem(currentPosition, false);
        tvImageCount.setText(currentPosition+1 + "/" + Urls.size());
        viewPagerPhoto.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                currentPosition = position;
                tvImageCount.setText(currentPosition + 1 + "/" + Urls.size());
            }
        });
    }


    @OnClick({R.id.view_pager_photo, R.id.tv_save_image_photo})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.view_pager_photo:
                break;
            case R.id.tv_save_image_photo:
                getbitmap(Urls.get(currentPosition));
                break;
        }
    }

    public Bitmap GetImageInputStream(String imageurl){
        URL url;
        HttpURLConnection connection=null;
        Bitmap bitmap=null;
        try {
            url = new URL("http://siminzhang.top:8088/city_home_server/public/static/posters/"+imageurl);
            connection=(HttpURLConnection)url.openConnection();
            connection.setConnectTimeout(6000); //超时设置
            connection.setDoInput(true);
            connection.setUseCaches(false); //设置不使用缓存
            InputStream inputStream=connection.getInputStream();
            bitmap=BitmapFactory.decodeStream(inputStream);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    private void getbitmap(final String path){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap= GetImageInputStream(path);
                if(saveimage(bitmap)){
                    Looper.prepare();
                    UIUtils.showToast(PhotoViewActivity.this,"保存成功",UIUtils.LENGTH_SHORT);
                    Looper.loop();
                }
            }
        }).start();
    }

    private boolean saveimage(Bitmap bitmap){
        String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/cityhome/downloadimg/";
        File appDir = new File(dir);
        if (!appDir.exists()) {
            /*mkdirs();//多级目录*/
            Boolean isSuccess= appDir.mkdirs();

        }
        //获取内部存储状态  
        String state = Environment.getExternalStorageState();
        //如果状态不是mounted，无法读写  
        if(!state.equals(Environment.MEDIA_MOUNTED)){
            return false;
        }
        Calendar now = new GregorianCalendar();
        SimpleDateFormat simpleDate = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
        String fileName = simpleDate.format(now.getTime());

        try {
            File file = new File(dir+fileName+".jpg");
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,out);
            out.flush();
            out.close();

            Uri uri = Uri.fromFile(file);
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,uri));
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


}
